package com.exam.controller;

import com.exam.domain.User;
import com.exam.domain.UserMessage;
import com.exam.service.interfaces.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jly on 2016/12/20.
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;


    @RequestMapping("view")
    public String view(){
        return "user/easytable";
    }
    /**
     * easyui table 分页测试
     * */
    @RequestMapping("/table")
    @ResponseBody
    public Map<String,Object> easytable(String page,String rows,String test){
        Map<String,Object> map = new HashMap<>();
        int total=userService.getTotal();
        List<User> fList=userService.getusers(Integer.valueOf(page),Integer.valueOf(rows));
        map.put("total", total);
        map.put("rows", fList);
        return map;
    }




    public static String basePath(HttpServletRequest request) {
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + path;
        return basePath;
    }

    /**
     * 获取项目根路径
     *
     * @Since: 2016-12-20
     * @author: jly
     */
    @ModelAttribute(name = "basePath")
    public String baseURL(HttpServletRequest request) {
        return basePath(request);
    }

    /**
     * 用户登录
     *
     * @param:  userName 用户名
     *          userPassword 密码
     *          basePath 项目根路径
     * @Since: 2016-12-20
     * @author: jly
     */
    @RequestMapping(path = "/login", method = RequestMethod.POST)
    @ResponseBody
    public boolean login(@Param("userName") String userName,
                         @Param("userPassword") String Password,
                         @ModelAttribute(name = "basePath") String basePath,
                         HttpSession session) {
        User message = userService.loginMessage(userName);
        String password = userService.selectPassowrdByUserName(userName);
        if (message != null) {
            session.setAttribute("userId",message.getUserId());
            session.setAttribute("message", message);
            session.setAttribute("roleName", message.getRole().getRoleName());
            session.setAttribute("userName", message.getUserName());
            session.setAttribute("roleId",message.getRole().getRoleId());
        }
        if (Password.equals(password)) {
            return true;
        }
        return false;
    }

    /**
     * 退出登录,返回到登录页面
     *
     * @Since: 2016-12-21
     * @author: jly
     */
    @RequestMapping("/loginout")
    public String loginout(HttpServletRequest request) {
        request.getSession().removeAttribute("userId");
        request.getSession().removeAttribute("message");
        request.getSession().removeAttribute("roleName");
        request.getSession().removeAttribute("userName");
        request.getSession().removeAttribute("roleId");
        return "redirect:" + basePath(request);

    }

    /**
     * 登陆后跳转到主页，并显示个人信息
     * 如果没有登录，跳转到登录页面
     *
     * @Since: 2016-12-20
     * @author: jly
     */
    @RequestMapping("index")
    public String indexPage(HttpSession session, HttpServletRequest request, Model model) {
        int roleid = (int) session.getAttribute("roleId");
        if (session.getAttribute("userName") == null) {
            return "redirect:" + basePath(request);
        }
        if(roleid == 1){
            return "redirect:" + basePath(request) + "/user/userLists";
        }
        if(roleid == 2){
            return "redirect:" + basePath(request) + "/grade/teacherGradeView";
        }
        //学生登录直接进入考试页面
        if(roleid == 3){
            return "redirect:" + basePath(request) + "/studentExamController/studentExamView";
        }
        return null;
    }

    /**
     * 个人信息链接显示页面
     *
     * @param: username
     * @return: userMessage相关信息
     * @since: 2016-12-21
     * @author: jly
     */
    @RequestMapping("/usermessage")
    public String userMessage(HttpSession session, Model model) {
        String username = (String) session.getAttribute("userName");
        UserMessage userMessage = userService.userInfo(username);
        model.addAttribute("userMassage", userMessage);
        return "user/usermessage";
    }

    /**
     * 修改个人信息
     *
     * @param:  username 用户名
     *          name 姓名
     *          mail 邮箱
     * @since: 2016-12-21
     * @author: jly
     * */
    @RequestMapping("/updateUserMessage")
    @ResponseBody
    public boolean updateUserInfo(String username, String name, String mail){
        if((username != null) && (userService.updateUserInfo(username,name,mail))){
            return true;
        }
        return false;
    }

    /**
     * 跳转到修改密码界面
     *
     * @since: 2016-12-21
     * @author: jly
     */
    @RequestMapping("/updatePasswordview")
    public String updatePasswordView() {
        return "user/updatepassword";
    }

    /**
     * 修改密码
     *
     * @param:  oldpsw 旧密码
     *          newpsw 新密码
     *          confirmpsw 确认的新密码
     * @since: 2016-12-21
     * @author: jly
     */
    @RequestMapping("/updatePassword")
    @ResponseBody
    public boolean updatePassword(String oldpsw, String newpsw, String confirmpsw, HttpSession session) {
        String username = (String) session.getAttribute("userName");
        String password = userService.selectPassowrdByUserName(username);
        if ((username != null) && (oldpsw.equals(password))) {
            if (newpsw.equals(confirmpsw)) {
                if (userService.updatePassowrd(newpsw, username)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 进入用户列表界面
     *
     * @return: 进入用户列表界面
     * @since: 2017-2-7
     * @author: jly
     * */
    @RequestMapping("/userLists")
    public String userList(HttpSession session, HttpServletRequest request){
        if (session.getAttribute("userName") == null) {
            return "redirect:" + basePath(request);
        }
        return "user/userList";
    }

    /**
     * 查看用户列表具体数据
     *
     * @return: 返回用户列表及相关信息
     * @since: 2017-2-7
     * @author: jly
     * */
    @RequestMapping("/List")
    @ResponseBody
    public List<UserMessage> tabList(Model model, String username, String name, int roleId){
       try {
           List<UserMessage> userList = userService.userList(username,name,roleId);
           model.addAttribute("userList",userList);
           return userList;
       }catch (Exception e){
           e.printStackTrace();
       }
       return null;
    }

    /**
     * 进入添加用户界面
     *
     * @since: 2017-2-12
     * @author: jly
     * */
    @RequestMapping("/adduser")
    public String addUser(HttpSession session,HttpServletRequest request){
        if (session.getAttribute("userName") == null) {
            return "redirect:" + basePath(request);
        }
        return "user/adduser";
    }

    /**
     * 判断用户名是否已经存在
     *
     * @return: int result> 0 存在
     * @Since: 2017-2-12
     * @author: jly
     * */
    public int userExist(String username){
        return userService.userExist(username);
    }

    /**
     * 添加用户具体操作
     *
     * @return: 返回操作成功与否
     * @since: 2017-2-12
     * @author: jly
     * */
    @RequestMapping("/adduserOperate")
    @ResponseBody
    public boolean addUserOperate(String username, String name, int roleid, String mail){
        int result = userExist(username);
        if(result == 0){
            if(userService.addUserOperate(username,name,roleid,mail)){
                return true;
            }
            return false;
        }
        return false;
    }

    /**
     * 管理员修改用户信息（姓名，角色，邮箱）
     *
     * @return: boolean 是否修改成功
     * @Since: 2017-2-12
     * @author: jly
     * */
    @RequestMapping("/modifyuser")
    @ResponseBody
    public boolean modifyUserMessage(String truename, String mail, int role, int userId){
        if(userService.modifyUserMessage(truename,mail,role,userId)){
            return true;
        }
        return false;
    }

    /**
     * 删除用户
     *
     * @return: boolean 是否删除成功
     * @Since: 2017-2-13
     * @author: jly
     * */
    @RequestMapping("/deleteUser")
    @ResponseBody
    public boolean deleteUser(int userid){
        if(userService.deleteUser(userid)){
            return true;
        }
        return false;
    }
}
